"""
-------------------------------------------------
    Author: Csm
    Date：2021-03-02 16:03
-------------------------------------------------
"""
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
from channels.security.websocket import AllowedHostsOriginValidator

from django.urls import path
from zanhu.messager.consumers import MessagesConsumer
from zanhu.notifications.consumers import NotificationsConsumer

# self.scope['type']获取协议类型
# self.scope['url_route']['kwargs']['username']获取URL中关键字参数
# channels routing 是scope级别的，一个连接只能由一个consumer接收和处理


application = ProtocolTypeRouter({
    # 'http':views,
    # 普通的HTTP请求不用手动写，框架会自动加载
    'websocket': AllowedHostsOriginValidator(
        AuthMiddlewareStack(
            URLRouter([
                path('ws/notifications/', NotificationsConsumer),
                path('ws/<str:username>/', MessagesConsumer),
            ])
        )
    )
})

"""
from channels.security.websocket import OriginValidator
AllowedHostOriginValidator，OriginValidator可以防止通过websocket进行CSRF攻击
OriginValidator需要手动添加ALLOW_HOST访问的源站
使用AllowedHostOriginValidator，允许访问的源站和Settings文件中的ALLOWED_HOST相同

AuthMiddlewareStack用于WebSocket认证，集成了CookieMiddleware，SessionMiddleware
Authmiddleware, 兼容Django认证系统
"""
